import {Notification} from 'element-ui'
import {getToken} from '@/utils/auth';

export function exportFile(data, callback) {
  const {url, params, method = "GET", suffix, fileName, download = true} = data;
  const request = new XMLHttpRequest();
  const message = '<span class="el-icon-loading"></span> ' + "正在导出" + fileName;
  let notifyLoading = Notification({
    dangerouslyUseHTMLString: true,
    duration: 0,
    message
  });
  request.open(method, method === "GET" ? url + params : url, true);
  request.responseType = 'blob';
  request.setRequestHeader('Content-Type', 'application/json');
  request.setRequestHeader("h5ve", getToken());
  request.onload = () => {
    callback && callback();
    if (download) {
      const data = request.response;
      const blob = new Blob([data]);
      const blobUrl = window.URL.createObjectURL(blob);
      const aLabel = document.createElement('a');
      aLabel.style.display = 'none';
      aLabel.download = fileName + new Date().getTime() + suffix;
      aLabel.href = blobUrl;
      aLabel.click();
      try {
        document.body.removeChild(aLabel);
      } catch (e) {
      }
      notifyLoading.close();
    }
  };
  request.send(method === "GET" ? null : JSON.stringify(params));
}

export function exportLocalFile(data, callback) {
  const {url, params, suffix, fileName, download = true} = data;
  const message = '<span class="el-icon-loading"></span> ' + "正在下载" + fileName;
  let notifyLoading = Notification({
    dangerouslyUseHTMLString: true,
    duration: 0,
    message
  });
  const aLabel = document.createElement('a');
  aLabel.style.display = 'none';
  aLabel.download = fileName + suffix;
  aLabel.href = url;
  aLabel.click();
  try {
    document.body.removeChild(aLabel);
  } catch (e) {
  }
  notifyLoading.close();
}
